# Create your views here.
from django.shortcuts import get_list_or_404, get_object_or_404, render_to_response
from django.template import RequestContext
from django.contrib.gis.shortcuts import render_to_kml
from chicago.models import  *
from geopy import geocoders  
from django.conf import settings
from django.contrib.gis.geos import *
from django.views.decorators.cache import cache_page



def do_kml(request, template, model, id=None):
    """
    The DRY function.
    """
    if id:
        qs = model.objects.filter(pk=id).kml()
        #obj = get_object_or_404(model, pk=id).kml()
    else:
        qs = model.objects.all().kml() 
        
    return render_to_kml(template, {'places' : qs}) 

# cache the kml data for 30 days, it rarely changes. 
@cache_page(60 * 60 * 24 * 30)
def wards_kml(request, id=None):
    return do_kml(request, "chicago/kml/wards.kml", Ward, id)

@cache_page(60 * 60 * 24 * 30)
def house_kml(request, id=None):
    return do_kml(request, "chicago/kml/house.kml", House, id)

@cache_page(60 * 60 * 24 * 30)
def senate_kml(request, id=None):
    return do_kml(request, 'chicago/kml/senate.kml', Senate, id)

@cache_page(60 * 60 * 24 * 30)
def tifs_kml(request, id=None):
    return do_kml(request, "chicago/kml/tifs.kml", TIFS, id)

@cache_page(60 * 60 * 24 * 30)
def congress_kml(request, id=None):
    return do_kml(request, "chicago/kml/congress.kml", Congress, id)

def ward_detail(request, ward, template_name="ward_detail.html"): 

    ward = get_object_or_404(Ward,ward=ward)

    return render_to_response( 
            template_name, 
            {'ward': ward}, 
            context_instance=RequestContext(request),
           )

def wards_map(request):
    lcount = Ward.objects.all().count()
    return render_to_response(
            'chicago/wards_map.html', 
            {'location_count' : lcount}) 
